# -*- coding: utf-8 -*-
from django import forms

from google.appengine.ext.db import djangoforms
from google.appengine.ext import db

from base.models import KTeacher, School
from base.util.decorators import render_to, login_required, admin_required
import logging


@login_required
@render_to('kteacher/list.html')
def list(request):
    query = KTeacher.gql('order by name ASC')
    kteachers = query.fetch(100)
    return {'kteachers': kteachers}

class KTeacherForm(djangoforms.ModelForm):
    class Meta:
        model = KTeacher
        exclude = ('id',)

#    def clean(self):
#        cleaned_data = self.cleaned_data
#        name = cleaned_data.get('name')
#        if ETeacher.is_existed(name):
#            raise forms.ValidationError(u'You already have the same school\'s name')
#        return cleaned_data

@admin_required
@render_to('kteacher/form.html')
def create(request):
    data = request.POST.copy()
    school_id = data.get('school', '').strip()
    form = KTeacherForm()
    if request.method == 'POST':
        form = KTeacherForm(request.POST)
        if form.is_valid():
            kteacher = form.save(commit=False)
            kteacher.put()
            school = School.get_using_id(int(school_id))
            school.kteacher = kteacher
            school.put()
            return kteacher.get_absolute_url
    return {'form': form}

@admin_required
@render_to('kteacher/detail.html')
def detail(request, kteacher_id):
    kteacher =  KTeacher.get_using_id(int(kteacher_id))
    return {
        'kteacher': kteacher,
        }

@admin_required
@render_to('kteacher/form.html')
def change(request, kteacher_id):
    kteacher = KTeacher.get_using_id(int(kteacher_id))
    form = KTeacherForm(request.POST or None, instance=kteacher)
    if form.is_valid():
        kteacher = form.save()
        return kteacher.get_absolute_url
    return {'form': form}


